package top.chukongxiang.dubboboot.simple.gateway.oauth2;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import top.chukongxiang.dubboboot.simple.common.service.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


@Component("userDetailsService")
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @DubboReference
    private UserService userService;

    @Resource
    private HttpServletRequest request;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO 身份校验，密码模式推荐传入password进行验证
        String password = request.getParameter("password");
        if (StringUtils.isEmpty(password)) {
            throw new BadCredentialsException("用户名或密码错误");
        }
        return new UserInfo(username, passwordEncoder.encode(password));
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    public HttpServletRequest getRequest() {
        return request;
    }
}
